package com.atguigu.lease.web.admin.schedule;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.model.entity.GraphInfo;
import com.atguigu.lease.model.entity.LeaseAgreement;
import com.atguigu.lease.model.enums.LeaseStatus;
import com.atguigu.lease.web.admin.service.GraphInfoService;
import com.atguigu.lease.web.admin.service.LeaseAgreementService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import io.minio.MinioClient;
import io.minio.RemoveObjectArgs;
import io.minio.RemoveObjectsArgs;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;

/*
*  日程计划类(定时任务类)
* */
@Component
public class ScheduledTasks {
   @Autowired
    LeaseAgreementService leaseAgreementService;
   @Autowired
    MinioClient minioClient;
   @Autowired
    MinioProperties minioProperties;
   @Autowired
    GraphInfoService graphInfoService;
    /*
    *  自动检查租约状态（2已签约，5.退租待确认）,
    *  如果租约到期(lease_end_date 租约结束日期 小于 当前日期) 自动把状态设置为已到期(4)
    *  lease_end_date 2024-10-9      2024-9-23(now())
    * */

   // @Scheduled(cron = "0/2 * * * * *")
    public  void checkStatus(){
        System.out.println("修改状态"+new Date());
        leaseAgreementService.update(new LambdaUpdateWrapper<LeaseAgreement>()
                        .in(LeaseAgreement::getStatus, LeaseStatus.SIGNED,LeaseStatus.WITHDRAWING)
                        .lt(LeaseAgreement::getLeaseEndDate,new Date())
                        .set(LeaseAgreement::getStatus,LeaseStatus.EXPIRED)
        );

    }



   // @Scheduled(cron = "0/2 * * * * *")
    public  void removeMinioImage(){
        try {
            //查询被删除的图片信息(图片的名字)
       /*     List<GraphInfo> list = graphInfoService.list(new LambdaQueryWrapper<GraphInfo>().eq(GraphInfo::getIsDeleted, 1));
*/
         List<String> urlList1=    graphInfoService.listRemoveImage(); //is_deleted=1 的图片集合
            List<String> urlList0=    graphInfoService.listRemoveImage0(); //is_deleted=0 的图片的集合

            //求两个list集合的差集 (urlList1 减  urlList0)
            urlList1.removeAll(urlList0);

            for (String url : urlList1) {
                if(url!=null){
                    String fileName = url.substring(url.lastIndexOf("/") + 1);
                    minioClient.removeObject(RemoveObjectArgs.builder().bucket(minioProperties.getBucketName()).object(fileName).build());
                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
